<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import {
  fetchDeleteUserDept,
  fetchGetUserDeptList,
  fetchGetUserInfoById,
  fetchLogoutUserById,
  fetchUnlockUserById
} from '@/service/api';
import { useLoading } from '~/packages/hooks';
import { $t } from '@/locales';
import UserFormDrawer from '@/views/system/user/modules/user-form-drawer.vue';

const route = useRoute();
const id = ref<CommonType.IdType>('');

const { loading, startLoading, endLoading } = useLoading();

onMounted(async () => {
  id.value = route.query.id as string;
  try {
    startLoading();
    await getUserInfo();
    await getUserDeptList();
  } finally {
    endLoading();
  }
});

const userInfo = ref<Api.System.User.UserInfoRecord>();

// logout by user id
async function handleLogoutUserById() {
  const { error } = await fetchLogoutUserById(id.value);
  if (error) return;
  window.$message?.success($t('common.operateSuccess'));
}

// get user info
async function getUserInfo() {
  const { data, error } = await fetchGetUserInfoById(id.value);
  if (error) return;
  userInfo.value = data;
}

const userDeptList = ref<Api.System.User.UserDeptRecord[]>();

// get user department list
async function getUserDeptList() {
  const { data, error } = await fetchGetUserDeptList(id.value);
  if (error) return;
  userDeptList.value = data;
}

// 退出部门
async function handleDeleteUserDept(row: Api.System.User.UserDeptRecord) {
  const { error } = await fetchDeleteUserDept({
    userId: row.userId,
    deptId: row.deptId
  });
  if (error) return;
  window.$message?.success($t('common.operateSuccess'));
  await getUserDeptList();
}

// unlock user
async function handleUnlockUserById() {
  const { error } = await fetchUnlockUserById(userInfo?.value?.id || '');
  if (error) return;
  window.$message?.success($t('common.operateSuccess'));
  await getUserInfo();
}

// edit drawer show
const drawerVisible = ref<boolean>(false);

// 打开编辑
function openDrawer() {
  drawerVisible.value = true;
}
</script>

<template>
  <div v-loading="loading" class="flex flex-col gap-2">
    <ElCard class="card-wrapper">
      <ElCollapse :model-value="['user-info']">
        <ElCollapseItem title="基本信息" name="user-info">
          <ElDescriptions direction="vertical" :column="4" border>
            <ElDescriptionsItem :rowspan="2" :width="140" label="用户头像" align="center">
              <ElImage
                class="h-100px w-100px"
                src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
              />
            </ElDescriptionsItem>
            <ElDescriptionsItem label="姓名" :width="300">{{ userInfo?.fullname || '未填写' }}</ElDescriptionsItem>
            <ElDescriptionsItem label="性别" :width="300">{{ userInfo?.sexText || '未填写' }}</ElDescriptionsItem>
            <ElDescriptionsItem label="手机号码" :width="300">{{ userInfo?.mobile || '未填写' }}</ElDescriptionsItem>
            <ElDescriptionsItem label="电子邮箱">{{ userInfo?.email || '未填写' }}</ElDescriptionsItem>
            <ElDescriptionsItem label="证件号码">{{ userInfo?.idCode || '未填写' }}</ElDescriptionsItem>
            <ElDescriptionsItem label="备注">{{ userInfo?.remark || '未填写' }}</ElDescriptionsItem>
            <ElDescriptionsItem label="地址">
              {{ userInfo?.address || '未填写' }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </ElCollapseItem>
        <div class="mt2 flex justify-end">
          <ElButton size="small" type="primary" plain @click="openDrawer">修改</ElButton>
        </div>
      </ElCollapse>
    </ElCard>
    <ElCard class="card-wrapper">
      <ElCollapse>
        <ElCollapseItem title="登录信息">
          <ElDescriptions direction="vertical" :column="3" border>
            <ElDescriptionsItem label="用户名" :width="300">
              <div class="flex gap-2 flex-items-center">
                <div>{{ userInfo?.username }}</div>
                <div><ElTag type="success" size="small">在线</ElTag></div>
                <div v-if="userInfo?.online === 1">
                  <ElPopconfirm :title="$t('common.logoutConfirm')" @confirm="handleLogoutUserById">
                    <template #reference>
                      <ElButton type="primary" size="small" plain>{{ $t('common.logout') }}</ElButton>
                    </template>
                  </ElPopconfirm>
                </div>
              </div>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="用户昵称" :width="300">{{ userInfo?.nickname || '未填写' }}</ElDescriptionsItem>
            <ElDescriptionsItem label="用户状态" :width="300">
              {{ userInfo?.enabled === 1 ? $t('form.enabledOptions.enabled') : $t('form.enabledOptions.disabled') }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="密码更新时间">
              {{ userInfo?.pwdUpdateTime || '未填写' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="账户过期时间">
              {{ userInfo?.expiredTime || '不限制' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="账户状态" class-name="flex flex-items-center gap-2">
              <div :class="userInfo?.locked === 1 ? 'text-red' : 'text-green'">
                {{ userInfo?.locked === 1 ? '已锁定，无法登录' : '正常' }}
              </div>
              <div v-if="userInfo?.locked === 1">
                <ElPopconfirm title="是否解锁用户？" @confirm="handleUnlockUserById">
                  <template #reference>
                    <ElButton type="primary" size="small" plain>解锁</ElButton>
                  </template>
                </ElPopconfirm>
              </div>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="UnionId">{{ userInfo?.unionId || '无' }}</ElDescriptionsItem>
            <ElDescriptionsItem label="小程序OpenId">{{ userInfo?.mpOpenId || '无' }}</ElDescriptionsItem>
            <ElDescriptionsItem label="公众号OpenId">{{ userInfo?.pubOpenId || '无' }}</ElDescriptionsItem>
          </ElDescriptions>
        </ElCollapseItem>
      </ElCollapse>
    </ElCard>
    <ElCard class="card-wrapper">
      <ElCollapse>
        <ElCollapseItem title="所在部门" name="user_dept">
          <ElTable :data="userDeptList" empty-text="未加入部门" border>
            <ElTableColumn prop="deptText" label="所在部门" />
            <ElTableColumn prop="postText" label="工作岗位" />
            <ElTableColumn prop="createTime" label="加入时间" />
            <ElTableColumn fixed="right" label="操作" width="120">
              <template #default="{ row }">
                <ElPopconfirm title="是否退出部门？" @confirm="handleDeleteUserDept(row)">
                  <template #reference>
                    <ElButton type="danger" plain size="small">退出部门</ElButton>
                  </template>
                </ElPopconfirm>
              </template>
            </ElTableColumn>
          </ElTable>
        </ElCollapseItem>
      </ElCollapse>
    </ElCard>
    <UserFormDrawer v-model:visible="drawerVisible" operate-type="edit" :row-data="userInfo" @submitted="getUserInfo" />
  </div>
</template>

<style scoped>
.el-container {
  .el-header {
    height: fit-content;
  }
}
</style>
